package com.hook.analyse;

import android.app.*;
import android.content.*;
import android.content.pm.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.widget.AdapterView.*;
import com.hook.analyse.model.*;
import com.hook.analyse.util.*;
import java.util.*;
import android.support.v4.app.*;

public class MainActivity extends Activity 
{

	private ListView lv_app_list;
    private AppAdapter mAppAdapter;
    public Handler mHandler = new Handler();

	private ProgressDialog waitingDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

		verifyStoragePermissions(this);
		showWaitingDialog();
		lv_app_list =  findViewById(R.id.lv_app_list);
        mAppAdapter = new AppAdapter();
        lv_app_list.setAdapter(mAppAdapter);
		initAppList();
		lv_app_list.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
				{
					// TODO: Implement this method
					AppInfo app=(AppInfo) mAppAdapter.getItem(p3);
					showInputDialog(app.packageName, app.appName);
					Toast.makeText(getApplication(), app.appName, Toast.LENGTH_LONG).show();

				}


			});

    }

	private void showInputDialog(final String packageName, String appName)
	{

		AlertDialog.Builder customizeDialog = 
			new AlertDialog.Builder(MainActivity.this);
		final View dialogView = LayoutInflater.from(MainActivity.this)
			.inflate(R.layout.hook_input, null);
		customizeDialog.setTitle(appName + "-Hook事件添加");
		customizeDialog.setView(dialogView);
		customizeDialog.setPositiveButton("添加",
			new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					// 获取EditView中的输入内容
					EditText hookclass = dialogView.findViewById(R.id.hook_class);
					EditText hookmethod = dialogView.findViewById(R.id.hook_method);
					HDb hdb=HDb.getInstance(Config.hookEventPath);
					List<HookEventBean> data=(List<HookEventBean>)hdb.read(HookEventBean.class);
					data.add(new HookEventBean(packageName, hookclass.getText().toString().trim(), hookmethod.getText().toString().trim()));
					hdb.write(data);
					Toast.makeText(getApplication(), "设置成功", Toast.LENGTH_LONG).show();

				}
			});

		customizeDialog.setNegativeButton("取消", new DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface p1, int p2)
				{
				}
			});
		customizeDialog.show();
	}



	private void showWaitingDialog()
	{
		waitingDialog = 
			new ProgressDialog(MainActivity.this);
		waitingDialog.setTitle("提示");
		waitingDialog.setMessage("加载App列表中...");
		waitingDialog.setIndeterminate(true);
		waitingDialog.setCancelable(false);
		waitingDialog.show();
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu)
	{
        getMenuInflater().inflate(R.menu.menu, menu); //通过getMenuInflater()方法得到MenuInflater对象，再调用它的inflate()方法就可以给当前活动创建菜单了，第一个参数：用于指定我们通过哪一个资源文件来创建菜单；第二个参数：用于指定我们的菜单项将添加到哪一个Menu对象当中。
        return true; // true：允许创建的菜单显示出来，false：创建的菜单将无法显示。
    }

    /**
	 *菜单的点击事件
	 */
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
	{

        switch (item.getItemId())
		{
            case R.id.hook_event:

				Intent intent =new Intent(MainActivity.this, HookActivity.class);
				startActivity(intent);

                Toast.makeText(this, "你点击了 事件管理", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }

        return true;
    }


	private void initAppList()
	{
        new Thread(){
            @Override
            public void run()
			{
                super.run();
                //扫描得到APP列表
                final List<AppInfo> appInfos = Apptool.scanLocalInstallAppList(MainActivity.this.getPackageManager());
                mHandler.post(new Runnable() {
						@Override
						public void run()
						{
							mAppAdapter.setData(appInfos);
							waitingDialog.dismiss();
						}
					});
            }
        }.start();
    }


    class AppAdapter extends BaseAdapter
	{

        List<AppInfo> myAppInfos = new ArrayList<AppInfo>();

        public void setData(List<AppInfo> myAppInfos)
		{
            this.myAppInfos = myAppInfos;
            notifyDataSetChanged();
        }

        public List<AppInfo> getData()
		{
            return myAppInfos;
        }

        @Override
        public int getCount()
		{
            if (myAppInfos != null && myAppInfos.size() > 0)
			{
                return myAppInfos.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position)
		{
            if (myAppInfos != null && myAppInfos.size() > 0)
			{
                return myAppInfos.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position)
		{
            return 0;
        }



        @Override
        public View getView(int position, View convertView, ViewGroup parent)
		{
            ViewHolder mViewHolder;
            AppInfo myAppInfo = myAppInfos.get(position);
            if (convertView == null)
			{
                mViewHolder = new ViewHolder();
                convertView = LayoutInflater.from(getBaseContext()).inflate(R.layout.appinfo, null);
                mViewHolder.iv_app_icon = (ImageView) convertView.findViewById(R.id.iv_app_icon);
                mViewHolder.tx_app_name = (TextView) convertView.findViewById(R.id.tv_app_name);
				mViewHolder.tx_package_name = (TextView) convertView.findViewById(R.id.tv_package_name);
				convertView.setTag(mViewHolder);
            }
			else
			{
                mViewHolder = (ViewHolder) convertView.getTag();
            }
            mViewHolder.iv_app_icon.setImageDrawable(myAppInfo.img);
            mViewHolder.tx_app_name.setText(myAppInfo.appName);
			mViewHolder.tx_package_name.setText(myAppInfo.packageName);

            return convertView;
        }

        class ViewHolder
		{

            ImageView iv_app_icon;
            TextView tx_app_name;
			TextView tx_package_name;

        }
    }

	private static final int REQUEST_EXTERNAL_STORAGE = 1;

	private static String[] PERMISSIONS_STORAGE = {
        "android.permission.READ_EXTERNAL_STORAGE",
        "android.permission.WRITE_EXTERNAL_STORAGE" };

//然后通过一个函数来申请
	public static void verifyStoragePermissions(Activity activity)
	{
		try
		{
			//检测是否有写的权限
			int permission = ActivityCompat.checkSelfPermission(activity,
																"android.permission.WRITE_EXTERNAL_STORAGE");
			if (permission != PackageManager.PERMISSION_GRANTED)
			{
				// 没有写的权限，去申请写的权限，会弹出对话框
				ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}


}
